<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stripe Connect 账户管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 2.5em;
        }

        .header p {
            color: #666;
            font-size: 1.2em;
        }

        .tabs {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 2px solid #e1e5e9;
        }

        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
            font-weight: 600;
        }

        .tab.active {
            border-bottom-color: #667eea;
            color: #667eea;
        }

        .tab:hover {
            background: #f8f9fa;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
        }

        input, select, textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            padding: 15px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 10px;
            display: none;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .accounts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .account-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #667eea;
        }

        .account-card h3 {
            margin-bottom: 10px;
            color: #333;
        }

        .account-card p {
            margin-bottom: 5px;
            color: #666;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-badge.active {
            background: #d4edda;
            color: #155724;
        }

        .status-badge.pending {
            background: #fff3cd;
            color: #856404;
        }

        .payment-form {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }

        .amount-group {
            display: flex;
            gap: 10px;
        }

        .amount-group input {
            flex: 1;
        }

        .amount-group select {
            width: 100px;
        }

        .transactions-list {
            margin-top: 20px;
        }

        .transaction-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #667eea;
        }

        .transaction-item h4 {
            margin-bottom: 8px;
            color: #333;
        }

        .transaction-item p {
            margin-bottom: 3px;
            color: #666;
            font-size: 14px;
        }

        .account-actions {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e1e5e9;
        }

        .account-actions .btn {
            padding: 8px 16px;
            font-size: 14px;
            background: #28a745;
        }

        .account-actions .btn:hover {
            background: #218838;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔄 Stripe Connect 账户管理</h1>
            <p>用户A通过平台向用户B付款的完整解决方案</p>
        </div>

        <div class="tabs">
            <div class="tab active" onclick="switchTab('create-account')">创建Connect账户</div>
            <div class="tab" onclick="switchTab('payment')">发起付款</div>
            <div class="tab" onclick="switchTab('accounts')">账户管理</div>
            <div class="tab" onclick="switchTab('transactions')">交易记录</div>
        </div>

        <!-- 创建Connect账户 -->
        <div id="create-account" class="tab-content active">
            <h2>创建Connect账户（收款方）</h2>
            <form id="createAccountForm">
                <div class="form-group">
                    <label for="accountEmail">邮箱地址</label>
                    <input type="email" id="accountEmail" name="accountEmail" required placeholder="收款方邮箱地址">
                </div>

                <div class="form-group">
                    <label for="businessType">业务类型</label>
                    <select id="businessType" name="businessType">
                        <option value="individual">个人</option>
                        <option value="company">公司</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="country">国家/地区</label>
                    <select id="country" name="country">
                        <option value="US">美国</option>
                        <option value="CA">加拿大</option>
                        <option value="GB">英国</option>
                        <option value="AU">澳大利亚</option>
                        <option value="DE">德国</option>
                        <option value="FR">法国</option>
                        <option value="JP">日本</option>
                    </select>
                </div>

                <button type="submit" class="btn" id="createAccountBtn">
                    <span id="createAccountText">创建Connect账户</span>
                    <span id="createAccountSpinner" class="loading" style="display: none;"></span>
                </button>
            </form>

            <div id="accountStatus" class="status"></div>
        </div>

        <!-- 发起付款 -->
        <div id="payment" class="tab-content">
            <h2>发起付款（用户A向用户B付款）</h2>
            <form id="paymentForm">
                <div class="form-group">
                    <label for="connectAccountId">收款方Connect账户ID</label>
                    <input type="text" id="connectAccountId" name="connectAccountId" required placeholder="acct_xxx">
                </div>

                <div class="form-group">
                    <label for="paymentAmount">付款金额</label>
                    <div class="amount-group">
                        <input type="number" id="paymentAmount" name="paymentAmount" required placeholder="金额" min="1">
                        <select id="paymentCurrency" name="paymentCurrency">
                            <option value="usd">USD</option>
                            <option value="eur">EUR</option>
                            <option value="gbp">GBP</option>
                            <option value="jpy">JPY</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label for="customerEmail">付款方邮箱 (可选)</label>
                    <input type="email" id="customerEmail" name="customerEmail" placeholder="付款方邮箱地址">
                </div>

                <div class="form-group">
                    <label for="paymentDescription">付款描述</label>
                    <textarea id="paymentDescription" name="paymentDescription" placeholder="付款用途描述"></textarea>
                </div>

                <button type="submit" class="btn" id="paymentBtn">
                    <span id="paymentText">创建付款</span>
                    <span id="paymentSpinner" class="loading" style="display: none;"></span>
                </button>
            </form>

            <div id="paymentStatus" class="status"></div>

            <!-- Stripe支付表单 -->
            <div id="payment-form" class="payment-form" style="display: none;">
                <h3>完成付款</h3>
                <form id="stripe-payment-form">
                    <div id="card-element"></div>
                    <div id="card-errors" role="alert"></div>
                    <button type="submit" class="btn" id="submit-payment">
                        <span id="submit-text">确认付款</span>
                        <span id="submit-spinner" class="loading" style="display: none;"></span>
                    </button>
                </form>
            </div>
        </div>

        <!-- 账户管理 -->
        <div id="accounts" class="tab-content">
            <h2>Connect账户管理</h2>
            <button class="btn" onclick="loadAccounts()">刷新账户列表</button>
            
            <div id="accountsList" class="accounts-grid"></div>
        </div>

        <!-- 交易记录 -->
        <div id="transactions" class="tab-content">
            <h2>交易记录</h2>
            <div class="form-group">
                <label for="filterAccountId">筛选账户 (可选)</label>
                <input type="text" id="filterAccountId" name="filterAccountId" placeholder="Connect账户ID">
            </div>
            <button class="btn" onclick="loadTransactions()">加载交易记录</button>
            
            <div id="transactionsList" class="transactions-list"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8002';
        let currentPaymentIntent = null;

        // 初始化函数（现在不需要Stripe初始化）
        function initApp() {
            console.log('应用初始化完成');
        }

        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签的active类
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(tabName).classList.add('active');
            
            // 添加active类到选中的标签
            event.target.classList.add('active');
        }

        // 显示状态信息
        function showStatus(elementId, type, message) {
            const status = document.getElementById(elementId);
            status.className = `status ${type}`;
            status.innerHTML = message;
            status.style.display = 'block';
        }

        // 创建Connect账户
        document.getElementById('createAccountForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const btn = document.getElementById('createAccountBtn');
            const text = document.getElementById('createAccountText');
            const spinner = document.getElementById('createAccountSpinner');
            
            btn.disabled = true;
            text.textContent = '创建中...';
            spinner.style.display = 'inline-block';
            
            try {
                const formData = new FormData(e.target);
                const accountData = {
                    email: formData.get('accountEmail'),
                    business_type: formData.get('businessType'),
                    country: formData.get('country')
                };

                const response = await fetch(`${API_BASE_URL}/create-connect-account`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(accountData)
                });

                const result = await response.json();

                if (response.ok) {
                    let statusMessage = '';
                    if (result.message && result.message.includes('已存在')) {
                        const source = result.source || 'unknown';
                        statusMessage = `找到已存在的Connect账户！<br>
                        账户ID: ${result.account_id}<br>
                        邮箱: ${result.email}<br>
                        状态: ${result.status}<br>
                        来源: ${source === 'stripe' ? 'Stripe系统' : '本地数据库'}<br>
                        该账户已可以使用。`;
                    } else {
                        statusMessage = `Connect账户创建成功！<br>
                        账户ID: ${result.account_id}<br>
                        邮箱: ${result.email}<br>
                        状态: ${result.status}<br>
                        请保存账户ID用于后续操作。`;
                    }
                    showStatus('accountStatus', 'success', statusMessage);
                } else {
                    showStatus('accountStatus', 'error', `创建失败: ${result.detail || '未知错误'}`);
                }
            } catch (error) {
                console.error('Error:', error);
                showStatus('accountStatus', 'error', '网络错误，请检查服务器是否运行');
            } finally {
                btn.disabled = false;
                text.textContent = '创建Connect账户';
                spinner.style.display = 'none';
            }
        });

        // 创建付款
        document.getElementById('paymentForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const btn = document.getElementById('paymentBtn');
            const text = document.getElementById('paymentText');
            const spinner = document.getElementById('paymentSpinner');
            
            btn.disabled = true;
            text.textContent = '创建中...';
            spinner.style.display = 'inline-block';
            
            try {
                const formData = new FormData(e.target);
                const paymentData = {
                    amount: parseInt(formData.get('paymentAmount')) * 100, // 转换为分
                    currency: formData.get('paymentCurrency'),
                    connect_account_id: formData.get('connectAccountId'),
                    customer_email: formData.get('customerEmail') || null,
                    description: formData.get('paymentDescription') || null
                };

                const response = await fetch(`${API_BASE_URL}/create-payment-intent`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(paymentData)
                });

                const result = await response.json();

                if (response.ok) {
                    currentPaymentIntent = result.payment_intent_id;
                    showStatus('paymentStatus', 'success', 
                        `付款创建成功！<br>
                        付款ID: ${result.payment_intent_id}<br>
                        金额: ${(result.amount / 100).toFixed(2)} ${result.currency.toUpperCase()}<br>
                        状态: ${result.status}`);
                    
                    // 显示支付表单
                    document.getElementById('payment-form').style.display = 'block';
                    initPaymentForm();
                } else {
                    showStatus('paymentStatus', 'error', `创建失败: ${result.detail || '未知错误'}`);
                }
            } catch (error) {
                console.error('Error:', error);
                showStatus('paymentStatus', 'error', '网络错误，请检查服务器是否运行');
            } finally {
                btn.disabled = false;
                text.textContent = '创建付款';
                spinner.style.display = 'none';
            }
        });

        // 初始化支付表单
        function initPaymentForm() {
            // 创建简单的信用卡输入表单
            const paymentForm = document.getElementById('payment-form');
            paymentForm.innerHTML = `
                <h3>完成付款</h3>
                <form id="credit-card-form">
                    <div class="form-group">
                        <label for="card-number">卡号</label>
                        <input type="text" id="card-number" placeholder="4242 4242 4242 4242" maxlength="19">
                        <small style="color: #666; font-size: 12px;">测试卡号: 4242424242424242 (Visa), 5555555555554444 (Mastercard)</small>
                    </div>
                    <div class="form-group">
                        <label for="card-expiry">有效期</label>
                        <input type="text" id="card-expiry" placeholder="MM/YY" maxlength="5">
                    </div>
                    <div class="form-group">
                        <label for="card-cvc">CVC</label>
                        <input type="text" id="card-cvc" placeholder="123" maxlength="4">
                    </div>
                    <div class="form-group">
                        <label for="card-name">持卡人姓名</label>
                        <input type="text" id="card-name" placeholder="John Doe">
                    </div>
                    <div id="card-errors" style="color: red; margin-bottom: 10px;"></div>
                    <button type="submit" class="btn" id="submit-payment">
                        <span id="submit-text">确认付款</span>
                        <span id="submit-spinner" class="loading" style="display: none;"></span>
                    </button>
                </form>
            `;

            // 处理表单提交
            document.getElementById('credit-card-form').addEventListener('submit', async function(event) {
                event.preventDefault();

                const submitBtn = document.getElementById('submit-payment');
                const submitText = document.getElementById('submit-text');
                const submitSpinner = document.getElementById('submit-spinner');
                const errorElement = document.getElementById('card-errors');

                submitBtn.disabled = true;
                submitText.textContent = '处理中...';
                submitSpinner.style.display = 'inline-block';
                errorElement.textContent = '';

                try {
                    // 获取卡片信息
                    const cardNumber = document.getElementById('card-number').value.replace(/\s/g, '');
                    const cardExpiry = document.getElementById('card-expiry').value;
                    const cardCvc = document.getElementById('card-cvc').value;
                    const cardName = document.getElementById('card-name').value;

                    // 验证输入
                    if (!cardNumber || !cardExpiry || !cardCvc || !cardName) {
                        errorElement.textContent = '请填写所有必填字段';
                        return;
                    }

                    // 解析有效期
                    const [expMonth, expYear] = cardExpiry.split('/');
                    if (!expMonth || !expYear) {
                        errorElement.textContent = '请输入正确的有效期格式 (MM/YY)';
                        return;
                    }

                    // 1. 创建支付方式
                    const paymentMethodResponse = await fetch(`${API_BASE_URL}/create-payment-method`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            type: 'card',
                            card: {
                                number: cardNumber,
                                exp_month: parseInt(expMonth),
                                exp_year: parseInt('20' + expYear),
                                cvc: cardCvc
                            },
                            billing_details: {
                                name: cardName
                            },
                            use_test_token: true  // 使用测试令牌，避免直接发送卡号
                        })
                    });

                    const paymentMethodResult = await paymentMethodResponse.json();

                    if (!paymentMethodResponse.ok) {
                        errorElement.textContent = paymentMethodResult.detail || '创建支付方式失败';
                        return;
                    }

                    // 2. 确认付款
                    const confirmResponse = await fetch(`${API_BASE_URL}/confirm-payment`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            payment_intent_id: currentPaymentIntent,
                            payment_method_id: paymentMethodResult.payment_method_id
                        })
                    });

                    const confirmResult = await confirmResponse.json();

                    if (confirmResponse.ok) {
                        if (confirmResult.status === 'succeeded') {
                            showStatus('paymentStatus', 'success', '付款成功！资金已转移到收款方账户。');
                            document.getElementById('payment-form').style.display = 'none';
                        } else if (confirmResult.status === 'requires_action') {
                            // 3. 处理3D Secure认证
                            const cardConfirmResponse = await fetch(`${API_BASE_URL}/confirm-card-payment`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    payment_intent_id: currentPaymentIntent,
                                    payment_method_id: paymentMethodResult.payment_method_id
                                })
                            });

                            const cardConfirmResult = await cardConfirmResponse.json();

                            if (cardConfirmResponse.ok) {
                                if (cardConfirmResult.status === 'succeeded') {
                                    showStatus('paymentStatus', 'success', '付款成功！资金已转移到收款方账户。');
                                    document.getElementById('payment-form').style.display = 'none';
                                } else if (cardConfirmResult.status === 'requires_action') {
                                    // 需要重定向到3D Secure认证页面
                                    if (cardConfirmResult.next_action && cardConfirmResult.next_action.type === 'redirect_to_url') {
                                        showStatus('paymentStatus', 'info', '正在跳转到3D Secure认证页面...');
                                        window.location.href = cardConfirmResult.next_action.redirect_to_url.url;
                                    } else {
                                        showStatus('paymentStatus', 'info', `需要额外认证: ${cardConfirmResult.status}`);
                                    }
                                } else {
                                    showStatus('paymentStatus', 'info', `付款状态: ${cardConfirmResult.status}`);
                                }
                            } else {
                                errorElement.textContent = cardConfirmResult.detail || '3D Secure认证失败';
                            }
                        } else {
                            showStatus('paymentStatus', 'info', `付款状态: ${confirmResult.status}`);
                        }
                    } else {
                        errorElement.textContent = confirmResult.detail || '付款失败';
                    }
                } catch (error) {
                    console.error('Error:', error);
                    errorElement.textContent = '网络错误，请重试';
                } finally {
                    submitBtn.disabled = false;
                    submitText.textContent = '确认付款';
                    submitSpinner.style.display = 'none';
                }
            });
        }

        // 获取账户设置链接
        async function getAccountLink(accountId) {
            try {
                const response = await fetch(`${API_BASE_URL}/account-link/${accountId}`);
                const result = await response.json();

                if (response.ok) {
                    // 打开账户设置链接
                    const newWindow = window.open(result.url, '_blank');
                    
                    if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {
                        // 如果弹窗被阻止，显示链接
                        alert(`账户设置链接已生成！\n\n请复制以下链接到浏览器中打开：\n${result.url}\n\n链接有效期：${new Date(result.expires_at * 1000).toLocaleString()}`);
                    } else {
                        alert('账户设置页面已在新窗口中打开，请完成账户设置。');
                    }
                } else {
                    alert(`获取账户设置链接失败: ${result.detail || '未知错误'}`);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('获取账户设置链接失败，请检查网络连接。');
            }
        }

        // 加载账户列表
        async function loadAccounts() {
            try {
                const response = await fetch(`${API_BASE_URL}/accounts`);
                const result = await response.json();

                if (response.ok) {
                    displayAccounts(result.accounts);
                } else {
                    console.error('加载账户失败:', result.detail);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // 显示账户列表
        function displayAccounts(accounts) {
            const container = document.getElementById('accountsList');
            
            if (accounts.length === 0) {
                container.innerHTML = '<p>暂无Connect账户</p>';
                return;
            }

            container.innerHTML = accounts.map(account => `
                <div class="account-card">
                    <h3>${account.email}</h3>
                    <p><strong>账户ID:</strong> ${account.account_id}</p>
                    <p><strong>国家:</strong> ${account.country}</p>
                    <p><strong>业务类型:</strong> ${account.business_type}</p>
                    <p><strong>状态:</strong> 
                        <span class="status-badge ${account.charges_enabled ? 'active' : 'pending'}">
                            ${account.charges_enabled ? '已激活' : '待激活'}
                        </span>
                    </p>
                    <p><strong>收款功能:</strong> ${account.charges_enabled ? '✅ 已启用' : '❌ 未启用'}</p>
                    <p><strong>提现功能:</strong> ${account.payouts_enabled ? '✅ 已启用' : '❌ 未启用'}</p>
                    <div class="account-actions">
                        ${!account.charges_enabled ? 
                            `<button class="btn" onclick="getAccountLink('${account.account_id}')">获取账户设置链接</button>
                             <button class="btn" onclick="getAccountDiagnostics('${account.account_id}')" style="background: #ff9800; margin-left: 10px;">诊断账户问题</button>` : 
                            '<span class="status-badge active">账户已激活</span>'
                        }
                    </div>
                </div>
            `).join('');
        }

        // 加载交易记录
        async function loadTransactions() {
            try {
                const filterAccountId = document.getElementById('filterAccountId').value;
                const url = filterAccountId ? 
                    `${API_BASE_URL}/payment-intents?connect_account_id=${filterAccountId}` : 
                    `${API_BASE_URL}/payment-intents`;

                const response = await fetch(url);
                const result = await response.json();

                if (response.ok) {
                    displayTransactions(result.payment_intents);
                } else {
                    console.error('加载交易记录失败:', result.detail);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // 显示交易记录
        function displayTransactions(transactions) {
            const container = document.getElementById('transactionsList');
            
            if (transactions.length === 0) {
                container.innerHTML = '<p>暂无交易记录</p>';
                return;
            }

            container.innerHTML = transactions.map(tx => `
                <div class="transaction-item">
                    <h4>付款ID: ${tx.payment_intent_id}</h4>
                    <p><strong>金额:</strong> ${(tx.amount / 100).toFixed(2)} ${tx.currency.toUpperCase()}</p>
                    <p><strong>状态:</strong> ${tx.status}</p>
                    <p><strong>收款方:</strong> ${tx.transfer_data?.destination || 'N/A'}</p>
                    <p><strong>平台费用:</strong> ${tx.application_fee_amount ? (tx.application_fee_amount / 100).toFixed(2) : 'N/A'}</p>
                    <p><strong>创建时间:</strong> ${new Date(tx.created_at * 1000).toLocaleString()}</p>
                </div>
            `).join('');
        }

        // 页面加载时初始化
        window.addEventListener('load', function() {
            initApp();
            
            // 检查URL参数，处理支付返回
            const urlParams = new URLSearchParams(window.location.search);
            const payment_intent = urlParams.get('payment_intent');
            const payment_intent_client_secret = urlParams.get('payment_intent_client_secret');
            
            if (payment_intent) {
                // 处理支付返回
                handlePaymentReturn(payment_intent);
            }
        });

        // 处理支付返回
        async function handlePaymentReturn(paymentIntentId) {
            try {
                const response = await fetch(`${API_BASE_URL}/payment/return?session_id=${paymentIntentId}`);
                const result = await response.json();
                
                if (result.status === 'success') {
                    showStatus('paymentStatus', 'success', `支付成功！金额: ${(result.amount / 100).toFixed(2)} ${result.currency.toUpperCase()}`);
                } else if (result.status === 'failed') {
                    showStatus('paymentStatus', 'error', '支付失败，请重试');
                } else {
                    showStatus('paymentStatus', 'info', result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                showStatus('paymentStatus', 'error', '获取支付状态失败');
            }
        }
    </script>
</body>
</html>
